<template>
  <div ref="chartContainer" class="chart"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { fetchProductPriceDistribution } from '@/api/data';

const chartContainer = ref(null);
let chartInstance = null;

const option = ref({
  title: {
    text: '商品价格分布(玫瑰图)',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    left: 'center',
    top: 'bottom',
    data: []
  },
  series: [
    {
      name: '价格区间',
      type: 'pie',
      radius: [30, 120],
      center: ['50%', '50%'],
      roseType: 'area',
      itemStyle: {
        borderRadius: 8
      },
      data: []
    }
  ]
});

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    chartInstance.setOption(option.value);
    
    // 响应式调整大小
    const resizeObserver = new ResizeObserver(() => {
      chartInstance?.resize();
    });
    resizeObserver.observe(chartContainer.value);
    
    // 组件卸载时清理
    onBeforeUnmount(() => {
      resizeObserver.disconnect();
      chartInstance?.dispose();
    });
  }
};

// 更新图表数据
const updateChart = async () => {
  const data = await fetchProductPriceDistribution();
  option.value.legend.data = data.map(item => item.range);
  option.value.series[0].data = data.map(item => ({
    value: item.count,
    name: item.range
  }));
  
  if (chartInstance) {
    chartInstance.setOption(option.value);
  }
};

onMounted(() => {
  initChart();
  updateChart();
});

// 监听option变化
watch(option, (newVal) => {
  if (chartInstance) {
    chartInstance.setOption(newVal, true);
  }
}, { deep: true });
</script>

<style scoped>
.chart {
  height: 100%;
  width: 100%;
  min-height: 500px; /* 玫瑰图需要足够高度 */
}
</style>